package com.ruoyi.alert.job;

import com.ruoyi.alert.domain.Alert;
import com.ruoyi.alert.domain.WaterQualityRecord;
import com.ruoyi.alert.mapper.WaterQualityMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class WaterQualityMonitorJob {

    private final WaterQualityMapper waterQualityMapper;
    private final RabbitTemplate rabbitTemplate;

    @Value("${alarm.cod.threshold:500.0}")
    private double codThreshold;

    public WaterQualityMonitorJob(WaterQualityMapper waterQualityMapper,
                                  RabbitTemplate rabbitTemplate) {
        this.waterQualityMapper = waterQualityMapper;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Scheduled(fixedRateString = "${alarm.cod.check-interval:5000}")
    public void checkCodChange() {

        List<WaterQualityRecord> records = waterQualityMapper.selectLatestRecordsGroupByProject();

        for (WaterQualityRecord record : records) {
            if (record.getPreviousCod() != null) {
                BigDecimal current = BigDecimal.valueOf(record.getCurrentCod());
                BigDecimal previous = BigDecimal.valueOf(record.getPreviousCod());
                BigDecimal diff = current.subtract(previous).abs();

                if (diff.compareTo(BigDecimal.valueOf(codThreshold)) >= 0) {
                    sendAlert(record, diff.doubleValue());
                }
            }
        }
    }

    private void sendAlert(WaterQualityRecord record, double diff) {
        Alert alert = new Alert();
        alert.setProjectId(record.getProjectId());
        alert.setProjectName(record.getProjectName());
        alert.setCodValueDay1(record.getPreviousCod());
        alert.setCodValueDay2(record.getCurrentCod());
        alert.setDiffValue(diff);
        alert.setDate(record.getCurrentRecordTime());

        rabbitTemplate.convertAndSend("alarm.exchange", "alarm.routingkey", alert);
    }
}